package com.example.sistemacompras;

import com.example.sistemacompras.adapter.BuyListAdapter;
import com.example.sistemacompras.db.DatabaseHandler;
import com.example.sistemacompras.entity.Client;
import com.example.sistemacompras.entity.Order;
import com.example.sistemacompras.entity.OrderDetail;
import com.example.sistemacompras.entity.Product;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class UserHomeActivity extends Activity {
	private int mId;

	private ListView list;

	private Order mOrder;

	private List<OrderDetail> mOrderDetails;

	private BuyListAdapter adapter;

	private Client mClient;

	private DatabaseHandler db;

	private Button searchButton;

	private EditText searchTag;

	private ImageView cartImageView;

	private TextView qtdItensCart;

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_user_home);
		db = new DatabaseHandler(getApplicationContext());
		list = (ListView) findViewById(R.id.home_list);
		mId = (Integer) getIntent().getExtras().get("user_id");

		searchTag = (EditText) findViewById(R.id.search_tag);
		searchButton = (Button) findViewById(R.id.search_button);

		searchButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				search(searchTag.getText().toString());

			}
		});
		loadClient();

		search("");
		qtdItensCart = (TextView) findViewById(R.id.textView_itens_in_cart);
		if (mOrderDetails == null || mOrderDetails.size() == 0) {
			qtdItensCart.setText("");
		} else {
			qtdItensCart.setText(String.valueOf(mOrderDetails.size()));
		}


	}

	private void loadClient() {
		TextView greeting = (TextView) findViewById(R.id.greeting_message);
		mClient = db.getClientById(mId);
		greeting.setText(greeting.getText() + " " + mClient.getName());
		if (mClient.getPhoto() != null) {
			BitmapDrawable drawable = new BitmapDrawable(this.getResources(),
					mClient.getPhoto());
			((ImageView) findViewById(R.id.user_image_view))
					.setScaleType(ImageView.ScaleType.FIT_CENTER);
			((ImageView) findViewById(R.id.user_image_view))
					.setBackgroundDrawable(drawable);

		}
		if (mOrder == null) {
			mOrder = db.getOrderByClient(mClient);
		}

		mOrderDetails = new ArrayList<OrderDetail>();
		if (mOrder != null) {
			mOrderDetails = db.getOrderDetailsByOrder(mOrder);

		}
		ImageView cartImageView = (ImageView) findViewById(R.id.cart_image_view);
		cartImageView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mOrderDetails != null && mOrderDetails.size() > 0) {

					Intent intent = new Intent(getApplicationContext(),
							CartActivity.class);
					intent.putExtra("user_id", mClient.getId());
					intent.putExtra("order_id", mOrderDetails.get(0).getOrder()
							.getId());
					startActivity(intent);
				} else {
					Toast.makeText(getApplicationContext(),
							"Nenhum produto no carrinho!", Toast.LENGTH_LONG)
							.show();
				}
			}
		});

	}

	/**
     * 
     */
	private List<Product> search(String searchValue) {
		final List<Product> nomes = db.getProductByName(searchValue);

		adapter = new BuyListAdapter(this, R.layout.products_adapter, nomes);

		list.setAdapter(adapter);

		list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					final int position, long id) {
				final Product product = nomes.get(position);
				if (product.getQtdStock() - 1 < 0) {
					Toast.makeText(getApplicationContext(), "Produto Esgotado",
							Toast.LENGTH_SHORT).show();
					;
					return;
				}

				final Dialog dialog = new Dialog(UserHomeActivity.this);
				dialog.setContentView(R.layout.product_sell_dialog);
				dialog.setTitle(product.getName());

				TextView price = (TextView) dialog
						.findViewById(R.id.txt_product_price);
				TextView stock = (TextView) dialog
						.findViewById(R.id.txt_product_stock);
				ImageView photo = (ImageView) dialog
						.findViewById(R.id.imv_product_photo);
				TextView descr = (TextView) dialog
						.findViewById(R.id.txt_product_descr);
				price.setText("R$ " + String.valueOf(product.getUnitValue()));
				stock.setText("Estoque:  "
						+ String.valueOf(product.getQtdStock()));
				photo.setImageBitmap(product.getPhoto());
				descr.setText("Descrição: \n "
						+ String.valueOf(product.getDescription()));

				Button buyButton = (Button) dialog.findViewById(R.id.btn_buy);
				buyButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						buyProduct(product);
						dialog.dismiss();
					}

				});

				Button deleteButton = (Button) dialog
						.findViewById(R.id.btn_cancel);
				deleteButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});

				dialog.show();

			}
		});

		return null;
	}

	private void buyProduct(Product product) {

		product.setQtdStock(product.getQtdStock() - 1);
		db.updateProduct(product);

		if (mOrder == null) {
			mOrder = new Order();
			mOrder.setClient(mClient);
			db.createOrder(mOrder);
		}

		if (mOrderDetails == null) {
			mOrderDetails = new ArrayList<OrderDetail>();
		}
		OrderDetail od = new OrderDetail();
		od.setOrder(mOrder);
		od.setProduct(product);
		// TODO change this when theres an edittext
		od.setQtd(1);
		// TODO need improvements...
		for (OrderDetail odTemp : mOrderDetails) {
			if (odTemp.getProduct().getId() == od.getProduct().getId()
					&& odTemp.getOrder().getClient().getId() == od.getOrder()
							.getClient().getId()
					&& od.getOrder().isSubmited() == 0) {
				od.setQtd(odTemp.getQtd() + 1);
			}
		}
		mOrderDetails.add(od);
		db.createOrderDetail(od);
		qtdItensCart.setText(String.valueOf(mOrderDetails.size()));
		// Creating or Updating the cart.

	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		loadClient();

		search("");
	}

	public void showUserProfile(View view) {
		Intent intent = new Intent(this, UserProfileActivity.class);
		intent.putExtra("user_id", mClient.getId());
		startActivityForResult(intent, 1);
		finish();
	}

	@Override
	protected void onResume() {
		super.onResume();
		search("");
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		loadClient();
		search("");
	}

}
